#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <error.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>


using namespace std;
#define MAX 1024

int main()
{
    //创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n == 0);
    (void)n;  //防止release下，编译器报警

    //创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        perror("fork");
        return 1;
    }

    //子写父读， 关闭不需要的fd，创建单向通信的管道
    if(id == 0)
    {//child
        close(pipefd[0]);//子进程关闭读端
        int cnt = 4;
        // int size = 0;
        while(true)
        {
            // char ch = 'a';
            // write(pipefd[1], &ch, 1);
            // size++;
            char message[MAX];
            snprintf(message, sizeof(message), "hello father, I am child process, pid : %d, cnt : %d", getpid(), cnt);
            write(pipefd[1], message, strlen(message));
            write(pipefd[1], message, 1);
            // if(cnt == 0) break;
            cnt--;
            sleep(1);
            cout << "write ...." << cnt << endl;
        }
        close(pipefd[1]);
        exit(0);
    }

    //parent
    close(pipefd[1]);//父进程关闭写端
    char buffer[MAX];
    while(true)
    {
        // sleep(200);
        ssize_t n = read(pipefd[0], buffer,  517);
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "child say: " << buffer << endl;
        }

        if(n == 0)
        {
            cout << "child quit, me too" << endl;
            close(pipefd[0]);
            break;
        }
        // cout << "father return n : " << n << endl;
        //exit(0);
        break;
    }

    cout << "write point close" << endl;
    close(pipefd[0]);
    sleep(5);

    int status;
    pid_t rid = waitpid(id, &status, 0);
    if(rid == id)
    {
        cout << "wait success" << endl;
        cout << "exit code: " << (status&0x7f) << endl;
    }
    return 0;
}
